# 导入requests模块
import requests
# 导入时间模块
import time
# 导入文字转语音模块
import pyttsx3
# 导入gui界面模块
import tkinter as tk


def create_gui():
    # 创建画板
    root = tk.Tk()
    # 设置界面标题
    root.title('弹幕工具')
    # 设置文本组件
    text = tk.Text(root, font=('微软雅黑', 12))
    # 布局
    text.pack()
    # 设置数据
    update_data(text)

    # 展示画板
    root.mainloop()


def get_response(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36'
    }
    response = requests.get(url=url, headers=headers)
    return response


def main():
    try:
        create_gui()
    except:
        pass


def update_data(text):
    # 清空文本
    text.delete(1.0, tk.END)
    # 创建一个语音合成引擎
    engine = pyttsx3.init()
    url = 'https://api.live.bilibili.com/xlive/web-room/v1/dM/gethistory?roomid=22957791&room_type=0'
    for i in range(100):
        response = get_response(url)
        room_list = response.json()['data']['room']

        for index in room_list:
            content = index['text']  # 弹幕内容
            name = index['nickname']  # 用户昵称
            date = index['timeline']  # 时间
            data = f'[{date}]  {name}："{content}"'
            print(data)
            text.insert(tk.END, data + '\n')
            text.update()
            # 文字转语音
            engine.say(name + '说：' + content)
            # 播报
            engine.runAndWait()

            time.sleep(1)  # 延时1秒


if __name__ == '__main__':
    main()
